 /*
  * Copyright (c) 2021, 2023, yishun.cn All rights reserved.
  *
  */
 package cn.shun.config;

 import cn.shun.entity.CustomIdGenerator;
 import cn.shun.entity.IdWorker;
 import cn.shun.entity.SnowflakeIdWorker;
 import com.alibaba.druid.pool.DruidDataSource;
 import org.mybatis.spring.SqlSessionFactoryBean;
 import org.mybatis.spring.annotation.MapperScan;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.*;
 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

 /**
  * <p>Project: MyBatis2023 - MybatisConfig
  * <p>Powered by yishun On 2023-01-19 14:59:17
  *
  * @author yishun [2465734101@qq.com]
  * @version 1.0
  * @since 17
  */
 @Configuration
 @PropertySource("classpath:db.properties")
 //扫描有@Mapper注解的接口，主要解决单元测试报红
 @ComponentScan("cn.shun.mapper")
 //扫描包，在接口上可以不加@Mapper
 @MapperScan("cn.shun.mapper")
 public class MybatisConfig {
     @Value("${db.driver}")
     private String driver;
     @Value("${db.url}")
     private String url;
     @Value("${db.username}")
     private String username;
     @Value("${db.password}")
     private String password;
     @Autowired
     private SnowFlakeInterceptor sfi;

     @Bean(name = "ds")
     public DruidDataSource ds() {
         DruidDataSource ds = new DruidDataSource();
         ds.setDriverClassName(driver);
         ds.setUrl(url);
         ds.setUsername(username);
         ds.setPassword(password);
         return ds;
     }

     @Bean(name = "sf")
     public SqlSessionFactoryBean sf(DruidDataSource ds) {
         SqlSessionFactoryBean sf = new SqlSessionFactoryBean();
         sf.setDataSource(ds);
         //添加雪花算法插件
         sf.setPlugins(sfi);
         sf.setTypeAliasesPackage("cn.shun.entity");
         return sf;
     }
     @Bean
     public SnowFlakeInterceptor sfi(){
         return new SnowFlakeInterceptor();
     }


     @Bean("idgenerator") @Primary
     public CustomIdGenerator idGenerator(){
         return new CustomIdGenerator();
     }

     @Bean @Primary
     public SnowflakeIdWorker snowflakeIdWorker() {
         //配置雪花算法的机器id和数据中心id
         return new SnowflakeIdWorker(1, 1);
     }

     @Bean(name = "idw")
     public IdWorker idw() {
         return new IdWorker(1,1,2);
     }
 }
